<template>
	<el-dialog
		:title="dictTitle"
		:visible.sync="dictVisible"
		width="40%"
		:before-close="dialogBeforeClose"
		:close-on-click-modal="false"
		append-to-body
	>
		<el-form
			ref="form"
			:model="curItems"
			:rules="rules"
			label-width="80px"
			:inline="false"
			size="normal"
		>
			<el-form-item label="字典类型">
				<el-input v-model="curItems.type" disabled></el-input>
			</el-form-item>
			<el-form-item label="字典描述" prop="display">
				<el-input v-model="curItems.display"></el-input>
			</el-form-item>
			<el-form-item label="字典值" prop="value">
				<el-input v-model="curItems.value"></el-input>
			</el-form-item>
			<el-form-item label="排序" prop="sort">
				<!-- <el-input v-model="curItems.sort"></el-input> -->
				<el-input-number
					v-model="curItems.sort"
					size="small"
					:min="1"
					:max="99999"
					:step="1"
				>
				</el-input-number>
			</el-form-item>
			<el-form-item label="备注">
				<el-input
					v-model="curItems.remark"
					type="textarea"
					placeholder="请输入内容"
					:autosize="{ minRows: 2, maxRows: 4 }"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">确定</el-button>
				<el-button @click="cancel">取消</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>
</template>

<script>
import { getDictModel } from '@/http/dict'
export default {
	props: {
		dictVisible: {
			type: Boolean,
			default: false,
		},
		dictTitle: {
			type: String,
			default: '',
		},
		dictType: {
			type: String,
			default: '',
		},
		curItem: {
			type: Object,
			default: () => {
				return {}
			},
		},
	},
	data() {
		var valueValidator = this.valueFun
		return {
			rules: {
				display: [
					{ required: true, message: '请输入字典描述', trigger: 'blur' },
				],
				value: [
					{ required: true, message: '请输入字典值', trigger: 'blur' },
					{ validator: valueValidator, trigger: 'blur' },
				],
				sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
			},
		}
	},
	computed: {
		curItems() {
			return this.curItem
		},
	},
	methods: {
		valueFun(rule, value, callback) {
			getDictModel({ value: value, type: this.curItem.type }).then(
				({ data }) => {
					if (data?.head?.code == 200) {
						if (Object.keys(data?.data || {}).length > 0) {
							if (this.curItems.id != data.data.id) {
								callback(new Error('该编码已经存在'))
							} else {
								callback()
							}
						} else {
							callback()
						}
					}
				},
			)
		},
		dialogBeforeClose() {
			this.$emit('update:dictVisible', false)
			this.$nextTick(() => {
				this.$refs['form'].clearValidate()
			})
		},
		onSubmit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					this.$emit('onSubmit', { ...this.curItems }, this.dictType)
				} else {
					return false
				}
			})
		},
		cancel() {
			this.dialogBeforeClose()
		},
	},
}
</script>

<style lang="scss" scoped></style>
